package filedao

import (
	"errors"
	"fmt"
	"hft/Database/admin/file"
	"hft/Http/Models/dao"
	adminreq "hft/Http/Models/request/admin_req"
	"hft/Http/Services/base"
	"hft/e"
	"hft/global"
	"hft/tools"

	"gorm.io/gorm"
)

type File struct{}

func (f *File) List(account_id uint, paginate *adminreq.FilePage, ids []int, db *gorm.DB) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		return db.Scopes(f.Type(paginate.FileType, db)).Scopes(f.Name(paginate, db)).Where("dir_id IN (?)", ids).Where("account_id = ?", account_id).Order("create_time desc").Scopes(dao.Paginate(dao.Page(paginate.Page), db))
	}
}

func (f *File) Type(fileType string, db *gorm.DB) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if fileType == "image" {
			return db.Where("file_type IN (?)", []string{"image/jpg", "image/png", "image/jpeg", "image/gif", "image/webp"})
		} else if fileType == "video" {
			return db.Where("file_type IN (?)", []string{"video/mp4", "video/avi"})
		} else {
			return db
		}
	}
}

func (f *File) Name(paginate *adminreq.FilePage, db *gorm.DB) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if paginate.Filename == "" {
			return db
		} else {
			return db.Where("real_name LIKE ?", fmt.Sprintf("%v%%", paginate.Filename))
		}
	}
}

// 监听容量是否超出 false表示不超出 true表示超出
func (f *File) IsOverUserLimit(size int64, claims tools.BaseClaims, db *gorm.DB) (err error) {
	account, err := base.FindAccount(claims, global.OC_DB)
	if err != nil {
		return err
	}

	var totalSize int64

	err = db.Model(&file.File{}).Select("SUM(file_size)").Where("account_id = ?", account.ID).Scan(&totalSize).Error

	if err != nil {
		totalSize = 0
		return nil
	}

	var maxSave, _ = tools.ParseSize(global.OC_CONFIG.System.MaxSave)

	if totalSize+size > maxSave {
		return errors.New(e.OverMaxSave)
	}

	return nil
}

var FileDao = new(File)
